
/**
 * Created by 长春驿枫 on 2015/6/13.
 *
 */

!(function(){
    var __functionForTree=function () {
        Ladder.include(Ladder.BasicURL + "/third/zTree/zTree.css");
        Ladder.ztree = {
            //tree数据回馈
            handleTreeData: function (treeid, parentNode, responseData) {
                var type = Ladder.getType(responseData);
                if (type == "String") responseData = Ladder.toJSON(responseData);
                if (type == "Array") return responseData;
                if (responseData.statusCode != 200) return null;
                if (!responseData.hasOwnProperty("data")) return null;
                var dataarray = responseData.data;
                return dataarray;
            },
            //firstexpand: function (treeid) {
            //    var treeObj = $.fn.zTree.getZTreeObj(treeid);
            //    var nodes = treeObj.getNodes();
            //    treeObj.expandNode(nodes[0], true, false, false);
            //},
            /**
             * 重置Tree的数据
             * @param treewidget
             * @param data
             */
            resetNodes:function(treewidget,data){
                var zTree;
                if(Ladder.getType(treewidget)=="String"){//如果是文本选择器
                    zTree = $.fn.zTree.getZTreeObj(treewidget);
                }else{
                    zTree=treewidget;
                }
                var nodes = zTree.getNodes();
                for (var i = 0, l = nodes.length; i < l; i++) {
                    zTree.removeNode(nodes[i]);
                }
                zTree.addNodes(null, data, true);
                Ladder.ztree.expandFirst(zTree);
            },
            init: function (el, setting,data) {
                var $el = $(el);
                if ($el.length < 1) return false;
                if(!/ztree/.test($el.attr("class")))$el.addClass("ztree");
                var treesetting = {
                    async: {
                        url: "",
                        type: "post",
                        dataFilter: Ladder.ztree.handleTreeData,
                        enable: false
                    },
                    data: { key: { id: "id", name: "name", children: "children" } },
                    callback: {}
                };
                var type = Ladder.getType(setting);
                if (type == "String") {
                    treesetting.async.url = setting;
                }
                if (type == "Object") {
                    if (setting.hasOwnProperty("url")) {
                        treesetting.async.url = setting.url;
                    }
                    if (setting.hasOwnProperty("onClick")) {
                        treesetting.callback.onClick = setting.onClick
                    }
                    if (setting.hasOwnProperty("onDblClick")) {
                        treesetting.callback.onDblClick = setting.onDblClick
                    }
                    if (setting.hasOwnProperty("param")) {
                        treesetting.async.otherParam = setting.param;
                    }
                    if (setting.hasOwnProperty("id")) {
                        treesetting.data.key.id = setting.id;
                    }
                    if (setting.hasOwnProperty("name")) {
                        treesetting.data.key.name = setting.name;
                    }
                    treesetting = $.extend(treesetting, setting);
                    treesetting.async.enable=false;
                }
                if (treesetting.async.url) {
                    treesetting.async.url = Ladder.Service.parseUrl(treesetting.async.url);
                } else {
                    if(!data)return false;
                }
                var ztreeObj = $.fn.zTree.init($(el), treesetting, data);
                if(!treesetting.async.url)return ztreeObj;
                webajax(treesetting.async.url, setting.param, function (json) {
                    var data = Ladder.ztree.handleTreeData(null, null, json);
                    ztreeObj.addNodes(null, data, true);
                    var nodes = ztreeObj.getNodes();
                    if(setting.title){
                        var n=Ladder.data(treesetting,"data.key.name");
                        if(!n)n="name";
                        if(!nodes[n]){
                            nodes[0][n]=setting.title;
                            if(setting.icon){
                                nodes[0]["icon"]=setting.icon;
                            }
                            ztreeObj.updateNode(nodes[0]);
                        }
                    }
                    ztreeObj.expandNode(nodes[0], true, false, false);
                    if(nodes[0]){
                        var child=nodes[0].children;
                        while(child&&child.length==1){
                            ztreeObj.expandNode(child[0], true, false, false);
                            child=child[0].children;
                        }
                    }
                    if(setting.filterOrg){
                        Ladder.ztree.filterOrg(ztreeObj,setting.filterOrg);
                    }
                    if(setting.onFinished){
                        setting.onFinished(ztreeObj,nodes);
                    }
                    //var finishEvent=setting.finishEvent||setting.onFinished;
                    //if(finishEvent){
                    //    finishEvent(ztreeObj,nodes);
                    //}
                });
                return ztreeObj;
            },
            /**
             * 展开第一层
             * @param treewidget
             * @param data
             */
            expandFirst:function(treewidget,data){
                var zTree;
                if (Ladder.getType(treewidget) == "String") {//如果是文本选择器
                    zTree = $.fn.zTree.getZTreeObj(treewidget);
                } else {
                    zTree = treewidget;
                }
                var nodes = zTree.getNodes();
                zTree.expandNode(nodes[0], true, false, false);
                var child=nodes[0].children;
                while(child.length==1){
                    zTree.expandNode(child[0], true, false, false);
                    child=child[0].children;
                }
            },
            reload: function (ztreeObj) {
                var pid = arguments[1];//修改 操作完选中
                var treesetting = ztreeObj.setting;
                var nodes = ztreeObj.getNodes();
                for (var i = 0, l = nodes.length; i < l; i++) {
                    ztreeObj.removeNode(nodes[i]);
                }
                webajax(treesetting.async.url, treesetting.async.param, function (json) {
                    var data = Ladder.ztree.handleTreeData(null, null, json);
                    ztreeObj.addNodes(null, data, true);
                    var nodes = ztreeObj.getNodes();
                    var upNode = ztreeObj.getNodesByParam("id", pid, null);////修改 操作完选中
                    if (upNode != null) {
                        ztreeObj.expandNode(upNode[0], true, false, false);////修改 操作完选中
                        return;
                    }
                    ztreeObj.expandNode(nodes[0], true, false, false);
                });
            },
            /**
             * 按照组织架构进行过滤
             * @param treewidget 树组件，或者对象，或者树的ID，在ID的时不需要书写#符号
             */
            filterOrg:function(treewidget,option){
                var loginuser=Ladder.getStore("loginuser");
                if(!loginuser&&(!loginuser.departmentid&&!loginuser.companyid))return;
                var currentDID="";
                var c_or_d=0;//公司或部门
                if(/(company)/.test(option)){
                    //if(loginuser.cids.split(",").length>2){
                    //    c_or_d=1;
                    //    loginuser.companyid=loginuser.cids.replace(/'/g,"");
                    //}else{
                    //    currentDID= loginuser.companyid;
                    //}
                    currentDID= loginuser.companyid;
                }
                if(/(department)/.test(option)){
                    currentDID=loginuser.departmentid;
                }
                if(/all/.test(option)){
                    var conditionsql="useway='hr' and (";
                    conditionsql+="(type='post' and val='"+loginuser.pid+"') or";
                    conditionsql+="(type='department' and val='"+loginuser.departmentid+"') or";
                    conditionsql+="(type='company' and val='"+loginuser.companyid+"') or";
                    conditionsql+="(type='level' and val='"+loginuser.lid+"') or";
                    conditionsql+="(type='jobnumber' and val='"+loginuser.job_number+"')";
                    conditionsql+=")";
                    var orconfig = webajax(URLS.URL_GetData,{ tableName:"orgmanageConfig",condition:conditionsql});
                    if(orconfig.statusCode==200&&orconfig.data){
                        var _companys="";
                        var _departments="";
                        for(var i=0;i<orconfig.data.length;i++){
                            if(orconfig.data[i].companys){
                                _companys+=orconfig.data[i].companys+",";
                            }
                            if(orconfig.data[i].departments){
                                _departments+=orconfig.data[i].departments+",";
                            }
                        }
                        _companys.replace(/,$/,"");
                        _departments.replace(/,$/,"");
                        if(_companys){
                            c_or_d=1;
                            loginuser.companyid=(loginuser.companyid?loginuser.companyid+",":"")+_companys;
                            //if(loginuser.companyid&&loginuser.companyid.length>0)
                            //    loginuser.companyid=loginuser.companyid+","+_companys;
                        }
                        if(_departments){
                            c_or_d+=2;
                            loginuser.departmentid=_departments;
                            //if(loginuser.departmentid&&loginuser.departmentid.length>0)
                            //loginuser.departmentid=loginuser.departmentid+","+_departments;
                        }
                    }
                }
                if(!/(department)|(company)|(all)/.test(option)||currentDID==""){
                    currentDID=loginuser.departmentid?loginuser.departmentid:loginuser.companyid;
                }
                var zTree;
                if (Ladder.getType(treewidget) == "String") {//如果是文本选择器
                    zTree = $.fn.zTree.getZTreeObj(treewidget);
                } else {
                    zTree = treewidget;
                }
                var showtreeList=[];
                switch (c_or_d) {
                    case 0:{
                        var owntree=zTree.getNodeByParam("id",currentDID);
                        while(owntree&&owntree.getParentNode()){
                            var p=owntree.getParentNode();
                            p.children=[owntree];
                            owntree=owntree.getParentNode();
                        }
                        if(owntree)showtreeList.push(owntree);
                        //else showtreeList.push(zTree.getNodes());
                    }
                        break;
                    case 1:{
                        var tids = loginuser.companyid.split(",");
                        for (var i = 0; i < tids.length; i++) {
                            if(tids[i].length<1)continue;
                            var owntree = zTree.getNodeByParam("id", tids[i]);
                            if(owntree)showtreeList.push(owntree);
                        }
                    }
                        break;
                    case 2:{
                        var tcids = loginuser.departmentid.split(",");
                        for (var i = 0; i < tcids.length; i++) {
                            if(tcids[i].length<1)continue;
                            var owntree = zTree.getNodeByParam("id", tcids[i]);
                            //寻找它的公司
                            var temp = owntree;
                            while (temp && temp.getParentNode()) {
                                temp = temp.getParentNode();
                                if (temp.tableName == "company") {
                                    temp.id = "-1";
                                    temp.children = [owntree];
                                    break;
                                }
                            }
                            showtreeList.push(temp);
                        }
                    }
                        break;
                    case 3:{
                        //既有公司所属又有部门所属
                        var tids = loginuser.companyid.split(",");
                        for (var i = 0; i < tids.length; i++) {
                            if(tids[i].length<1)continue;
                            var owntree = zTree.getNodeByParam("id", tids[i]);
                            if(owntree)showtreeList.push(owntree);
                        }
                        var tcids = loginuser.departmentid.split(",");
                        for (var i = 0; i < tcids.length; i++) {
                            if(tcids[i].length<1)continue;
                            var owntree = zTree.getNodeByParam("id", tcids[i]);
                            //寻找它的公司
                            var temp = owntree;
                            while (temp && temp.getParentNode()) {
                                temp = temp.getParentNode();
                                if (temp.tableName == "company") {
                                    temp.id = "-1";
                                    temp.children = [owntree];
                                    break;
                                }
                            }
                            showtreeList.push(temp);
                        }
                    }
                        break;
                }
                Ladder.ztree.resetNodes(zTree,showtreeList);
            },
            getChildrenIds:function(nodeData){
                var re_t=[];
                if(nodeData)getChilren(nodeData.id);
                function getChilren(node){
                    re_t.push(node.id);
                    if(node.children&&children.length>0){
                        for(var i=0;i<node.children.length;i++){
                            getChilren(node.children[i]);
                        }
                    }
                }
            }

        };
        Ladder.NS("Tree");
        /**
         * ###  树组件是2017年初书写,用以扩展ladder前端库，相比之下独特的地方在于，支持数据混排，这是很多第三方组件不具备
         * @param el
         * @param option
         * @constructor
         */
        Ladder.Tree=function(el,option){
            this.parent=null;
            this.rawData=null;
            /***
             *
             * @type {{url: string, param: null, indent: string, title: string, mode: string, idKey: string, pidKey: string, nameKey: string, cKey: string, data: null, onRender: null, onClick: null}}
             */
            this.settings={
                /**
                 *
                 */
                url:"",
                param:null,
                indent:"20px",
                title:"",
                search:false,
                /***
                 * 模式,children.pid,all
                 */
                mode:"children",//pid
                idKey:"id",
                pidKey:"pid",
                nameKey:"name",
                cKey:'children',
                data:null,
                onRender:null,
                onClick:null,
                onDblClick:null,
                skin:"dataview",
                switch:true
            };
            this.parent=$(el);
            if(this.parent.length<1)return;
            option=Ladder.toJSON(option);
            switch (Ladder.getType(option)){
                case "String":
                    this.settings.url=option;
                    break;
                case "Object":
                    $.extend(this.settings,option);
                    break;
            }
            if(this.settings.search!=false){
                var $div=$("<div style='margin:5px;'><span>条件:</span></div>").appendTo(this.parent);
                var $input=$("<input data-bind='"+this.settings.search+"'/>").appendTo($div);
                var $button=$("<button>搜索</button>").appendTo($div);
                $button.click(function () {
                    var condition=$input.val();
                    var $li=$(this).parent().parent().find("li");
                    if(condition){
                        $li.hide().each(function () {
                            var $span=$(this).find("span.yui-tree-node");
                            if($span.html().indexOf(condition)!=-1){
                                $span.parents("li").show();
                            }
                        });
                    }
                    else{
                        $li.show();
                    }

                    //alert(condition);
                })
            }
            if((this.parent[0].nodeName).toLowerCase()!="ul"){
                this.parent=$("<ul class='"+this.settings.skin+"'></ul>").appendTo(this.parent);
            }
            Ladder.include(Ladder.BasicURL+"/css/ladder.css");

            if(this.settings.pidKey&&this.settings.pidKey.indexOf(",")>-1){
                this.settings.pidKey=this.settings.pidKey.split(",");
            }
            if(this.settings.cKey&&this.settings.cKey.indexOf(",")>-1){
                this.settings.cKey=this.settings.cKey.split(",");
            }
            if(this.settings.nameKey&&this.settings.nameKey.indexOf(",")>-1){
                this.settings.nameKey=this.settings.nameKey.split(",");
            }
        }
        Ladder.Tree.prototype={

            init:function(){


            },
            /**
             * 填充数据
             * @param data
             */
            fillData:function(data,father){
                var me=this;
                if(!data)return;
                me.rawData=me.__deepcopy(data);
                var treeData=me.rawData;
                if(/(pid)|(all)/.test(me.settings.mode)){
                    treeData = me.arrayToTree(me.rawData);
                }
                if (!father) father = me.parent;
                father.empty();
                me.addNode(father, treeData);
            },
            /***
             * 添加节点
             * @param parent 父元素
             * @param data 数据
             */
            addNode:function(parent,data){
                var me = this;
                if (!parent) parent = me.parent;
                data.forEach(function(item){
                    var $li = $("<li></li>").appendTo(parent);
                    var title="";
                    if(me.settings.nameKey){
                        for (var i = 0; i < me.settings.nameKey.split(',').length; i++) {
                            title = title || item[me.settings.nameKey.split(',')[i]];
                            if(title)break;
                        }
                    }
                    //切换按钮
                    if(me.settings.switch){
                        var $switchbtn = $("<i class='iconfont switch switchopen'></i>").appendTo($li);
                        $switchbtn.click(function () {
                            var $pli=$(this).parent();
                            var $cul=$pli.find("ul");
                            if($cul.length<1)return;
                            //开->关
                            if($(this).hasClass("switchopen")){
                                me.expandNode($pli,0)
                            }else{
                                me.expandNode($pli,1)
                            }
                        });

                    }
                    var $span = $("<span class='yui-tree-node'>" +title + "</span>").appendTo($li);
                    if (me.settings.onRender) {
                        var ret = me.settings.onRender($span, item);
                        if (ret) $span.empty().append(ret);
                    }
                    $span.on("click.tree", function () {
                        //点击节点变色
                        me.parent.find("span").removeClass("current");
                        $span.addClass("current");
                        //自定义单击事件
                        if (me.settings.onClick) me.settings.onClick($span, item);
                    });
                    $span.on("dblclick.tree", function () {
                        //点击节点变色
                        me.parent.find("span").removeClass("current");
                        $span.addClass("current");
                        //自定义单击事件
                        if (me.settings.onDblClick) me.settings.onDblClick($span, item);
                    });
                    $span.data("data", item);
                    var ckey = null;
                    switch (Ladder.getType(me.settings.cKey)) {
                        case "String":
                            ckey = me.settings.cKey;
                            appendChildren(ckey);
                            break;
                        case "Array":
                            me.settings.cKey.forEach(function(ck) {
                                appendChildren(ck);
                            });
                            break;
                        default:
                            break;
                    }
                    function appendChildren(c) {
                        if (item[c] && item[c].length > 0) {
                            var $ul = $("<ul></ul>").appendTo($li);
                            me.addNode($ul, item[c]);
                        }
                    }
                });

                return parent;
            },
            /***
             *
             * @param records
             * @param data
             * @param idkey
             * @param ckey
             * @param pkey
             * @param pvalue
             * @returns {*}
             * @private
             */
            toRecord:function(data,idkey,ckey,pkey,pvalue){
                var me=this;
                var records={};
                if(Ladder.getType(data)!="Array")data=[data];
                if(!idkey)idkey=me.settings.idKey;
                if(!ckey)ckey=me.settings.cKey;
                if(!pkey)pkey=me.settings.pidKey;
                if(Ladder.getType(pkey)=="Array")pkey=pkey[0];
                _format(data,idkey,ckey,pkey,pvalue);
                function _format(data,idkey,ckey,pkey,pvalue){
                    for (var i = 0,len=data.length; i < len; i++)
                    {
                        var o = data[i];
                        var key = me.__repairKey(o[idkey]);
                        if(!key)continue;
                        records[key] = o;
                        if(pvalue&&pkey)records[key][pkey]=pvalue;
                        switch (Ladder.getType(ckey)) {
                            case "String":
                                if (o[ckey] && o[ckey].length > 0) {
                                    _format(o[ckey],idkey,ckey,pkey,key);
                                }
                                break;
                            case "Array":
                                var ck=undefined;
                                for(var t=0,max=ckey.length;t<max;t++){
                                    if(ckey[t]&&o[ckey[t]]){
                                        ck=ckey[t];
                                        break;
                                    }
                                }
                                if (ck&&o[ck] && o[ck].length > 0) {
                                    _format(o[ck],idkey,ckey,pkey,key);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                return records;
            },
            /**
             * 数组数据转换成Tree数据
             * @description 将ID、ParentID这种数据格式转换为树格式
             * @param data 源数据
             * @param id id的键名
             * @param pid 父级id的键名
             * @returns {Array} tree型数组
             */
            arrayToTree: function (data, id, pid){
                var me=this;
                if(!id)id=me.settings.idKey;
                if(!pid)pid=me.settings.pidKey;
                var childrenName =me.settings.cKey || "children";
                if (!data || !data.length || !id) return [];
                var targetData = [];//存储数据的容器(返回)
                var itemLength = data.length;//数据集合的个数
                //把原始分解成节点类型
                var records = me.toRecord(data);

                //执行tree数据构建
                for (var i = 0; i < itemLength; i++)
                {
                    var currentData = data[i];
                    switch (Ladder.getType(pid)){
                        case "String":
                            append(currentData[pid],currentData);
                            break;
                        case "Array":
                            pid.forEach(function(k){
                                append(currentData[k]);
                            });
                            break;
                    }
                }

                return targetData;
                function append(key,currentData){
                    key=me.__repairKey(key);
                    var parentData = records[key];
                    if (!parentData)
                    {
                        targetData.push(currentData);
                        return;
                    }
                    parentData[childrenName] = parentData[childrenName] || [];
                    parentData[childrenName].push(currentData);
                }
            },
            /***
             * 整理键的数据
             * @param key
             * @returns {*}
             * @private
             */
            __repairKey:function(key){
                if (typeof (key) == "string") key = key.replace(/[.]/g, '').toLowerCase();
                return key;
            },
            __deepcopy:function (data) {
                var me=this;
                var ret;
                switch(Ladder.getType(data)){
                    case "Array":
                        ret=[];
                        data.forEach(function(item,index){
                            ret[index]=me.__deepcopy(item);
                        });
                        return ret;
                    case "Object":
                        return $.extend({},data);
                    default:
                        return data;
                }
            },
            expandNode:function(node,flag){
                if(flag){
                    node.find("ul:eq(0)").show(500);
                    node.find("i:eq(0)").removeClass("switchclose").addClass("switchopen");
                }else{
                    node.find("ul:eq(0)").hide(500);
                    node.find("i:eq(0)").removeClass("switchopen").addClass("switchclose");
                }
            }
        }

        Ladder.NS("TreeDialog");
        Ladder.TreeDialog=function(el,option){
            this.id=Ladder.uuid();
            this.container = $("<div class='yui-treedialog' id='"+this.id+"'></div>").appendTo(document.body);
            this.tree=null;

            this.relation=null;
            this.settings={
                url:"",
                param:null,
                mode:"children",//pid
                idKey:"id",
                pidKey:"pid",
                nameKey:"name",
                cKey:'children',
                data:null,
                multiSelect:false,
                width:270,
                chooser:null
            };
            if(el&&$(el).length>0){
                this.relation=$(el);
                var z=Ladder.getMaxZ(this.relation);
                this.container.css("z-index",z+1);
            }
            $.extend(this.settings,option);
            if(this.settings.chooser){
                this.settings.chooser=Ladder.toJSON(this.settings.chooser);
                switch (Ladder.getType(this.settings.chooser)){
                    case "String":
                        this.settings.chooser={value:this.settings.chooser};
                        break;
                    case "Object":
                        break;
                    default:
                        this.settings.chooser=null;
                        break;
                }
            }


            this.init();
        };
        Ladder.TreeDialog.prototype={
            init:function(){
                var me=this;
                var $main=$('<div class="main"></div>').appendTo(me.container);
                //左侧的树
                $main.append('<div class="lefttree yui-tree"></div>');
                //操作按钮
                var $operation=$('<div class="operationview js-only">').appendTo($main);
                $('<i class="iconfont addoption">&#xe7cc;</i>').appendTo($operation);
                $('<i class="iconfont removeoption">&#xe7d9;</i>').appendTo($operation);
                //右侧多选
                var $select = $('<div class="rightselect js-only">').appendTo($main);
                $('<select class="select_multi" multiple="multiple" class="selectvalue"></select>').appendTo($select);
                $main.append('<div class="errorinfo"></div>');
                $main.append('<div class="bottomview"><button class="returnbtn">确定</button></div>');
                me.tree=new Ladder.Tree($main.find(".lefttree"),me.settings);
                if(me.settings.multiSelect){
                    me.container.width(535);
                    me.container.height(320);
                    $operation.show();
                    $select.show();
                    $main.find(".bottomview").show();
                }else{
                    me.container.width(me.settings.width);
                    me.container.find(".lefttree").width(me.settings.width);
                    if(me.settings.chooser&&me.relation){
                        me.tree.settings.onDblClick=function(node,data){
                            for(var p in me.settings.chooser){
                                var v=data[me.settings.chooser[p]];
                                me.relation.attr(p,v)
                                if(p=="value")me.relation.val(v);
                            }
                            me.container.hide(100);
                            $(document.body).off("click."+me.id);
                        }
                    }
                }




            },
            show:function(x,y){
                var me=this;
                if(!x&&me.relation)x=me.relation.offset().left;
                if(!y&&me.relation)y=me.relation.offset().top+me.relation.outerHeight();
                me.container.css({left:x,top:y}).show(100);
                setTimeout(function () {
                    $(document.body).on("click."+me.id,function (event) {
                        if($(event.target).parents(".yui-treedialog").attr("id")==me.id)return;
                        me.container.hide();
                        $(document.body).off("click."+me.id);
                    });
                },1500)


            }
        }

    };
    if(typeof define === "function" && define.amd){
        require.config({
            shim: {
                'zTree': ['core'],
                'exhide':['zTree']
            },
            paths: {
                'core': 'ladder-core',
                'zTree': '../third/ztree/jquery.ztree.all.min',
                'exhide': "../third/ztree/jquery.ztree.exhide.min"
            }
        });
        define(['exhide'],__functionForTree);
    }else{
        __functionForTree();
    }
})();
